package com.csii.oauth.filter.xss;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    HttpServletRequest orgRequest = null;
    private boolean isIncludeRichText = false;

    public XssHttpServletRequestWrapper(HttpServletRequest request, boolean isIncludeRichText) {
        super(request);
        orgRequest = request;
        this.isIncludeRichText = isIncludeRichText;
    }

    @Override
    public String getParameter(String name){
        Boolean flag = ("content".equals(name) || name.endsWith("WithHtml"));
        if (flag && !isIncludeRichText) {
            return super.getParameter(name);
        }
        name = JsoupUtil.clean(name);
        String value = super.getParameter(name);
        if (StringUtils.isNoneBlank(value)) {
            value = JsoupUtil.clean(value);
        }
        return value;
    }

    public String[] getParameterValue(String name){
        String[] arr = super.getParameterValues(name);
        if (arr != null) {
            for (int i=0;i<arr.length;i++) {
                arr[i] = JsoupUtil.clean(arr[i]);
            }
        }
        return  arr;
    }

    public String getHeader(String name){
        name = JsoupUtil.clean(name);
        String value = super.getHeader(name);
        if (StringUtils.isNoneBlank(value)) {
            value =  JsoupUtil.clean(value);
        }
        return value;
    }

    public HttpServletRequest getOrgRequest(){  return orgRequest; }

    public static HttpServletRequest getOrgRequest(HttpServletRequest req){
        if(req instanceof XssHttpServletRequestWrapper) {
            return ((XssHttpServletRequestWrapper) req).getOrgRequest();
        }
        return req;
    }
}
